package com.nec.recommend.utils;

import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONObject;
import com.nec.recommend.consts.URLConstant;
import com.nec.recommend.module.weapp.entity.WeappGetPhoneResult;
import com.nec.recommend.module.weapp.entity.WeappGetTokenResult;
import com.nec.recommend.module.weapp.entity.WeappLoginResult;
import com.nec.recommend.module.weapp.vo.WeappGetPhoneVO;
import com.nec.recommend.module.weapp.vo.WeappGetTokenVO;
import com.nec.recommend.module.weapp.vo.WeappLoginVO;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

public class WeappUtil {
    private static final RedisTemplate<String, Object> redisTemplate = SpringUtil.getBean("customRedisTemplate");

    public static WeappLoginResult login(WeappLoginVO weappLoginVO) {
        JSONObject result = RequestUtil.get(URLConstant.WEAPP_GET_LOGIN, weappLoginVO);
        return result.toBean(WeappLoginResult.class);
    }

    public static WeappGetPhoneResult getPhone(WeappGetPhoneVO weappGetPhoneVO) {
        JSONObject result = RequestUtil.post(URLConstant.WEAPP_POST_PHONE, new JSONObject() {{
            set("code", weappGetPhoneVO.getCode());
        }}, null, weappGetPhoneVO);
        JSONObject phone_info = result.getJSONObject("phone_info");
        return phone_info.toBean(WeappGetPhoneResult.class);
    }

    public static String getToken(WeappGetTokenVO weappGetTokenVO) {
        String access_token_key = "access_token";
        Object access_token_obj = redisTemplate.opsForValue().get(access_token_key);
        if (Objects.nonNull(access_token_obj)) {
            return (String) access_token_obj;
        }
        JSONObject result = RequestUtil.get(URLConstant.WEAPP_GET_TOKEN, weappGetTokenVO);
        WeappGetTokenResult tokenResult = result.toBean(WeappGetTokenResult.class);
        redisTemplate.opsForValue().set(access_token_key, tokenResult.getAccess_token(), tokenResult.getExpires_in(), TimeUnit.SECONDS);
        return tokenResult.getAccess_token();
    }
}
